#include <iostream>
#include <stdint.h>
#include <sys/timerfd.h>
#include <unistd.h>

int main()
{
	//用于提供单调递增的时间，不受系统时间调整
	int timefd = timerfd_create(CLOCK_MONOTONIC, 0);
	if (timefd < 0)
	{
		perror("timerfd_create error");
		return -1;
	}
	// int timerfd_settime(int fd, int flags,const struct itimerspec *new_value,struct itimerspec *_Nullable old_value);
	struct itimerspec n;
	// 设置第一次超时时间
	n.it_value.tv_sec = 1;
	n.it_value.tv_nsec = 0;
	// 设置第一次超时之后间隔时间
	n.it_interval.tv_sec = 1;
	n.it_interval.tv_nsec = 0;
	int f = timerfd_settime(timefd, 0, &n, nullptr);
	if (f < 0)
	{
		perror("timerfd_settime error");
		return -2;
	}
	time_t now = time(NULL);
	struct tm *local_time = localtime(&now); // 转换为本地时间（带时区）
	// struct tm *utc_time = gmtime(&now);		 // 转换为 UTC 时间
	while (true)
	{
		uint64_t timed = 0;
		ssize_t n = ::read(timefd, &timed, sizeof(timed));
		if (n < 0)
		{
			perror("read error");
			return -3;
		}
		std::cout << "距离上次超时时间过了" << time << "次" << "," << now << "," << time(NULL) << "," << (time(NULL) - now) << std::endl;
		std::cout << "当前本地时间：" 
              << local_time->tm_year + 1900 << "-"
              << local_time->tm_mon + 1 << "-"
              << local_time->tm_mday << " "
              << local_time->tm_hour << ":"
              << local_time->tm_min << ":"
              << local_time->tm_sec << std::endl;
	}
	::close(timefd);
	return 0;
}